import { useUserStore } from '@/store'


// 请求拦截
const requestInterceptors = (vm) => {
    uni.$uv.http.interceptors.request.use((config) => {
		const { token } = useUserStore()
		config.header['Content-Type'] = 'application/json'
		if(token) config.header.Authorization = `Bearer ${token}`
        console.log('请求拦截', config);
        return config
    }, (config) => Promise.reject(config))
}

// 响应拦截
const responseInterceptors = (vm) => {
    uni.$uv.http.interceptors.response.use((response) => {
		console.log('响应拦截', response);
		
		 if(response.statusCode === 200) {
			const data = response.data
			if(data && (data.code === 401)) {
				uni.hideLoading()
				uni.$uv.toast('登录已过期，请重新登录')
		        uni.reLaunch({ url: uni.$config.loginPage })
				return Promise.reject(response)
			}
			if(data && (data.code === 200 || data.code === 0)) return data
			
			uni.hideLoading()
			uni.$uv.toast(data.msg)
			return Promise.reject(data)
		} else {
			uni.hideLoading()
			uni.$uv.toast('服务器错误：' + response.statusCode)
			return Promise.reject(response)
		}
    }, async (response) => { /*  对响应错误做点什么 （statusCode !== 200）*/
		if(response.statusCode == 401) {
			uni.$uv.toast('登录已过期，请重新登录')
			const { logout_init } = useUserStore()
			await logout_init(false)
			uni.reLaunch({ url: uni.$config.loginPage })
		}
		uni.hideLoading()
        return Promise.reject(response)
    })
}

// 初始化请求配置
export const Request = ()=>{
	uni.$uv.http.setConfig((defaultConfig) => {
		const baseURL = uni.$config.platform === 'h5' ? uni.$config.proxy : uni.$config.baseUrl
		defaultConfig.timeout = 15000
	    defaultConfig.baseURL = baseURL
	    return defaultConfig
	})
	requestInterceptors();
	responseInterceptors();
}
